package main

import (
	"context"
	amqp "github.com/rabbitmq/amqp091-go"
	"os"
	"time"
	"zhongxc.cc/go-common/errs"
	"zhongxc.cc/go-common/mq"
	"zhongxc.cc/go-common/utils"
)

func NewTask() {
	conn := mq.NewRabbitMqConnection()
	channel, err := conn.Channel()
	errs.FailOnError(err, "Failed to open a channel")
	defer func(conn *amqp.Connection) {
		_ = conn.Close()
	}(conn)
	defer func(channel *amqp.Channel) {
		_ = channel.Close()
	}(channel)

	queue, err := channel.QueueDeclare(
		"task_queue",
		true, // 声明为持久队列
		false,
		false,
		false,
		nil,
	)
	errs.FailOnError(err, "Failed to declare a queue")
	body := utils.BodyFrom(os.Args) // 从参数中获取要发送的消息正文

	ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFunc()
	err = channel.PublishWithContext(ctx,
		"",
		queue.Name,
		false,
		false,
		amqp.Publishing{
			DeliveryMode: amqp.Persistent, // 持久（交互模式：瞬态/持久）
			ContentType:  "text/plain",
			Body:         []byte(body),
		},
	)
	errs.FailOnError(err, "Failed to publish a message")
}

func main() {
	NewTask()
}
